<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"kelvinzhang.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="引言闲暇时间抽个空写了个三国杀武将手册的小程序，中间有个需求设计的是合成武将皮肤图、竖排的武将姓名、以及小程序码，然后提供保存图片到相册，最终让用户可以分享到朋友圈或其他平台。合成图片应该按照Canvas的文档来做都没什么问题，主要是有个竖排文字的需求，这里和大家分享一下。">
<meta property="og:type" content="article">
<meta property="og:title" content="小程序利用Canvas绘制图片和竖排文字">
<meta property="og:url" content="https://kelvinzhang.gitee.io/2018/05/14/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%88%A9%E7%94%A8Canvas%E7%BB%98%E5%88%B6%E5%9B%BE%E7%89%87%E5%92%8C%E7%AB%96%E6%8E%92%E6%96%87%E5%AD%97/index.html">
<meta property="og:site_name" content="猿创日记">
<meta property="og:description" content="引言闲暇时间抽个空写了个三国杀武将手册的小程序，中间有个需求设计的是合成武将皮肤图、竖排的武将姓名、以及小程序码，然后提供保存图片到相册，最终让用户可以分享到朋友圈或其他平台。合成图片应该按照Canvas的文档来做都没什么问题，主要是有个竖排文字的需求，这里和大家分享一下。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/5/14/1635f1e3b5c1ccc4?w=258&h=258&f=jpeg&s=52521">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/5/14/1635f1ee2a33cc4e?w=564&h=786&f=jpeg&s=59275">
<meta property="og:image" content="https://user-gold-cdn.xitu.io/2018/5/14/1635f1f27875f56d?w=640&h=640&f=jpeg&s=69607">
<meta property="article:published_time" content="2018-05-14T13:53:44.000Z">
<meta property="article:modified_time" content="2021-08-26T11:56:30.575Z">
<meta property="article:author" content="Kelvin">
<meta property="article:tag" content="小程序, Canvas">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://user-gold-cdn.xitu.io/2018/5/14/1635f1e3b5c1ccc4?w=258&h=258&f=jpeg&s=52521">

<link rel="canonical" href="https://kelvinzhang.gitee.io/2018/05/14/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%88%A9%E7%94%A8Canvas%E7%BB%98%E5%88%B6%E5%9B%BE%E7%89%87%E5%92%8C%E7%AB%96%E6%8E%92%E6%96%87%E5%AD%97/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>小程序利用Canvas绘制图片和竖排文字 | 猿创日记</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">猿创日记</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/KelvinQQ" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://kelvinzhang.gitee.io/2018/05/14/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%88%A9%E7%94%A8Canvas%E7%BB%98%E5%88%B6%E5%9B%BE%E7%89%87%E5%92%8C%E7%AB%96%E6%8E%92%E6%96%87%E5%AD%97/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Kelvin">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="猿创日记">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          小程序利用Canvas绘制图片和竖排文字
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-05-14 21:53:44" itemprop="dateCreated datePublished" datetime="2018-05-14T21:53:44+08:00">2018-05-14</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-08-26 19:56:30" itemprop="dateModified" datetime="2021-08-26T19:56:30+08:00">2021-08-26</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h1><p>闲暇时间抽个空写了个三国杀武将手册的小程序，中间有个需求设计的是合成武将皮肤图、竖排的武将姓名、以及小程序码，然后提供保存图片到相册，最终让用户可以分享到朋友圈或其他平台。合成图片应该按照<code>Canvas</code>的文档来做都没什么问题，主要是有个竖排文字的需求，这里和大家分享一下。</p>
<span id="more"></span>

<h1 id="广告"><a href="#广告" class="headerlink" title="广告"></a>广告</h1><p>宣传一下自己的小程序，有喜欢三国杀的可以关注一下，有什么问题也可以加我微信一起讨论。</p>
<p><code>扫码体验小程序</code></p>
<p><img src="https://user-gold-cdn.xitu.io/2018/5/14/1635f1e3b5c1ccc4?w=258&h=258&f=jpeg&s=52521"></p>
<p><code>扫码添加好友，请备注：三国杀</code></p>
<p><img src="https://user-gold-cdn.xitu.io/2018/5/14/1635f1ee2a33cc4e?w=564&h=786&f=jpeg&s=59275"></p>
<h1 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h1><p>首先放一张最终保存到相册的图片吧~</p>
<p><img src="https://user-gold-cdn.xitu.io/2018/5/14/1635f1f27875f56d?w=640&h=640&f=jpeg&s=69607"></p>
<blockquote>
<p>自我感觉良好，至少达到了我自己的预期吧~~~</p>
</blockquote>
<p>下面让我们一步一步来看看如何实现的吧。</p>
<p>整个图片分为三个部分：</p>
<ol>
<li>武将图片</li>
<li>小程序码</li>
<li>武将文字信息</li>
</ol>
<p>先来看一下<code>wxml</code>里面的代码，主要是放了一个<code>canvas</code>标签，控制了一下高度和宽度属性。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;view&gt;</span><br><span class="line">  &lt;canvas class=&#x27;share-canvas&#x27; style=&quot;width:100%;height:&#123;&#123;canvasHeight&#125;&#125;px&quot; canvas-id=&quot;share_canvas&quot;&gt;&lt;/canvas&gt;</span><br><span class="line">&lt;/view&gt;</span><br></pre></td></tr></table></figure>

<h3 id="武将图片"><a href="#武将图片" class="headerlink" title="武将图片"></a>武将图片</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">drawHeroImage: function (path) &#123;</span><br><span class="line">    var that = this;</span><br><span class="line">    // 拿到canvas context</span><br><span class="line">    let ctx = wx.createCanvasContext(&#x27;share_canvas&#x27;);</span><br><span class="line">    // 为了保证图片比例以及绘制的位置，先要拿到图片的大小</span><br><span class="line">    wx.getImageInfo(&#123;</span><br><span class="line">      src: path,</span><br><span class="line">      success: function (res) &#123;</span><br><span class="line">			</span><br><span class="line">		  // 计算图片占比信息	</span><br><span class="line">        let maxWidth = Math.min(res.width, that.data.canvasWidth * 0.65);</span><br><span class="line">        let radio = maxWidth / res.width;</span><br><span class="line"></span><br><span class="line">        let offsetY = (that.data.canvasHeight - res.height * radio) / 2;</span><br><span class="line">        console.log(&#x27;offsetY=&#x27; + offsetY);</span><br><span class="line">        that.setData(&#123;</span><br><span class="line">          imageWidth: res.width * radio,</span><br><span class="line">          imageHeight: res.height * radio,</span><br><span class="line">          offsetY: offsetY,</span><br><span class="line">        &#125;);</span><br><span class="line">        </span><br><span class="line">        // 绘制canvas背景，不属于绘制图片部分</span><br><span class="line">        ctx.setFillStyle(&#x27;white&#x27;)</span><br><span class="line">        ctx.fillRect(0, 0, that.data.canvasWidth, that.data.canvasHeight);</span><br><span class="line">        // 绘制武将图片，path是本地路径，不可以传网络url，如果是网络图片需要先下载</span><br><span class="line">        ctx.drawImage(path, 10, offsetY, res.width * radio, res.height * radio)</span><br><span class="line">        // 绘制小程序码</span><br><span class="line">        that.drawQrCodeImage(ctx);</span><br><span class="line">        // 绘制势力汉字：吴</span><br><span class="line">        that.drawInfluence(ctx, that.data.hero.HERO.INFLUENCE);</span><br><span class="line">        // 绘制武将姓名：陆逊</span><br><span class="line">        that.drawName(ctx, that.data.hero.HERO.NAME);</span><br><span class="line">        // 绘制武将称号：江陵侯</span><br><span class="line">        that.drawHorner(ctx, that.data.hero.HERO.HORNER);</span><br><span class="line">        // 最终调用draw函数，生成预览图</span><br><span class="line">        // 一个坑点：只能调用一次，否则后面的会覆盖前面的</span><br><span class="line">        ctx.draw();</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<h3 id="小程序码"><a href="#小程序码" class="headerlink" title="小程序码"></a>小程序码</h3><p>小程序码和武将图片是一个类型，无非就是需要计算绘制的位置，这里就不再展示相关代码了。</p>
<h3 id="武将文字信息"><a href="#武将文字信息" class="headerlink" title="武将文字信息"></a>武将文字信息</h3><p>从刚刚的代码可以看出，我分了3个部分来绘制，其实<code>吴</code>和<code>陆逊</code>应该是可以放到一起的，但是我在绘制的时候发现，空格在绘制的时候会引起异常，导致空格后面的文字无法绘制出来，所以我这里<code>吴</code>和<code>陆逊</code>中间的空白是靠位置偏移来做的。</p>
<p>这里就展示一下如何绘制武将称号的。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">// 绘制武将称号：江陵侯</span><br><span class="line">drawHorner: function (ctx, text) &#123;</span><br><span class="line">	// 设置字号</span><br><span class="line">    ctx.setFontSize(26);</span><br><span class="line">    // 设置字体颜色</span><br><span class="line">    ctx.setFillStyle(&quot;#000000&quot;);</span><br><span class="line">    // 计算绘制起点</span><br><span class="line">    let x = this.data.offsetX + 35;</span><br><span class="line">    let y = this.data.offsetY + 10;</span><br><span class="line">    console.log(&#x27;drawHorner&#x27; + text);</span><br><span class="line">    console.log(x);</span><br><span class="line">    console.log(y);</span><br><span class="line">    // 绘制竖排文字，这里是个Util函数，具体实现请继续看</span><br><span class="line">    Canvas.drawTextVertical(ctx, text, x, y);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>绘制竖排文字从网上找了个开源的代码，需要看原理的请看<a target="_blank" rel="noopener" href="http://www.zhangxinxu.com/wordpress/?p=7362">这里</a></p>
<p>当然我这里为了适用小程序做了些改动，函数原型是这样子的：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CanvasRenderingContext2D.prototype.letterSpacingText = function (text, x, y, letterSpacing)</span><br></pre></td></tr></table></figure>

<p>原谅我不是很会<code>js</code>，完全不懂这是个什么语法，看了一会没弄懂，感觉像是给类添加新的属性，不管他。</p>
<blockquote>
<p>不管白猫黑猫，能抓到耗子就是好猫</p>
</blockquote>
<p>改造后的函数像下面的样子：</p>
<p><code>canvas.js</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">* @author zhangxinxu(.com)</span><br><span class="line">* @licence MIT</span><br><span class="line">* @description http://www.zhangxinxu.com/wordpress/?p=7362</span><br><span class="line">*/</span><br><span class="line">function drawTextVertical(context, text, x, y) &#123;</span><br><span class="line">  var arrText = text.split(&#x27;&#x27;);</span><br><span class="line">  var arrWidth = arrText.map(function (letter) &#123;</span><br><span class="line">    return 26;</span><br><span class="line">    // 这里为了找到那个空格的 bug 做了许多努力，不过似乎是白费力了</span><br><span class="line">    // const metrics = context.measureText(letter);</span><br><span class="line">    // console.log(metrics);</span><br><span class="line">    // const width = metrics.width;</span><br><span class="line">    // return width;</span><br><span class="line">  &#125;);</span><br><span class="line">  </span><br><span class="line">  var align = context.textAlign;</span><br><span class="line">  var baseline = context.textBaseline;</span><br><span class="line"></span><br><span class="line">  if (align == &#x27;left&#x27;) &#123;</span><br><span class="line">    x = x + Math.max.apply(null, arrWidth) / 2;</span><br><span class="line">  &#125; else if (align == &#x27;right&#x27;) &#123;</span><br><span class="line">    x = x - Math.max.apply(null, arrWidth) / 2;</span><br><span class="line">  &#125;</span><br><span class="line">  if (baseline == &#x27;bottom&#x27; || baseline == &#x27;alphabetic&#x27; || baseline == &#x27;ideographic&#x27;) &#123;</span><br><span class="line">    y = y - arrWidth[0] / 2;</span><br><span class="line">  &#125; else if (baseline == &#x27;top&#x27; || baseline == &#x27;hanging&#x27;) &#123;</span><br><span class="line">    y = y + arrWidth[0] / 2;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  context.textAlign = &#x27;center&#x27;;</span><br><span class="line">  context.textBaseline = &#x27;middle&#x27;;</span><br><span class="line"></span><br><span class="line">  // 开始逐字绘制</span><br><span class="line">  arrText.forEach(function (letter, index) &#123;</span><br><span class="line">    // 确定下一个字符的纵坐标位置</span><br><span class="line">    var letterWidth = arrWidth[index];</span><br><span class="line">    // 是否需要旋转判断</span><br><span class="line">    var code = letter.charCodeAt(0);</span><br><span class="line">    if (code &lt;= 256) &#123;</span><br><span class="line">      context.translate(x, y);</span><br><span class="line">      // 英文字符，旋转90°</span><br><span class="line">      context.rotate(90 * Math.PI / 180);</span><br><span class="line">      context.translate(-x, -y);</span><br><span class="line">    &#125; else if (index &gt; 0 &amp;&amp; text.charCodeAt(index - 1) &lt; 256) &#123;</span><br><span class="line">      // y修正</span><br><span class="line">      y = y + arrWidth[index - 1] / 2;</span><br><span class="line">    &#125;</span><br><span class="line">    context.fillText(letter, x, y);</span><br><span class="line">    // 旋转坐标系还原成初始态</span><br><span class="line">    context.setTransform(1, 0, 0, 1, 0, 0);</span><br><span class="line">    // 确定下一个字符的纵坐标位置</span><br><span class="line">    var letterWidth = arrWidth[index];</span><br><span class="line">    y = y + letterWidth;</span><br><span class="line">  &#125;);</span><br><span class="line">  // 水平垂直对齐方式还原</span><br><span class="line">  context.textAlign = align;</span><br><span class="line">  context.textBaseline = baseline;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">module.exports = &#123;</span><br><span class="line">  drawTextVertical: drawTextVertical</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="绘制网络图片"><a href="#绘制网络图片" class="headerlink" title="绘制网络图片"></a>绘制网络图片</h3><p>由于网络图片无法直接绘制，所以需要先下载到本地，然后再按住本地图片绘制的流程走一遍。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">downloadHeroImage: function () &#123;</span><br><span class="line">    // 微信不支持非https的图片下载，这里了个替换</span><br><span class="line">    let url = this.data.hero.HERO.ICON.replace(/http/, &quot;https&quot;);</span><br><span class="line">    var that = this;</span><br><span class="line">    wx.downloadFile(&#123;</span><br><span class="line">      url: url,</span><br><span class="line">      success: function (res) &#123;</span><br><span class="line">        // 下载成功后拿到图片的路径，然后开始绘制</span><br><span class="line">        var path = res.tempFilePath;</span><br><span class="line">        that.drawHeroImage(path);</span><br><span class="line">      &#125;, fail: function (res) &#123;</span><br><span class="line">        console.log(res)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<h3 id="保存图片"><a href="#保存图片" class="headerlink" title="保存图片"></a>保存图片</h3><p>说了这么多，自然少不了最终的一步，将绘制到<code>canvas</code>的图片保存到手机相册，这里需要用户授权，你需要自己处理。</p>
<p>用的是微信给我们提供的接口<code>wx.canvasToTempFilePath</code>。需要我们传入起点坐标<code>(x, y)</code>和画布大小<code>(width, height)</code>以及<code>canvasId</code>。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">saveShareImage: function () &#123;</span><br><span class="line">    wx.showLoading(&#123;</span><br><span class="line">      title: &#x27;正在保存图片..&#x27;,</span><br><span class="line">    &#125;);</span><br><span class="line">    let that = this;</span><br><span class="line">    wx.canvasToTempFilePath(&#123;</span><br><span class="line">      x: 0,</span><br><span class="line">      y: 0,</span><br><span class="line">      width: that.data.canvasWidth,</span><br><span class="line">      height: that.data.canvasHeight,</span><br><span class="line">      canvasId: &#x27;share_canvas&#x27;,</span><br><span class="line">      success: function (res) &#123;</span><br><span class="line">        wx.saveImageToPhotosAlbum(&#123;</span><br><span class="line">          filePath: res.tempFilePath,</span><br><span class="line">          success(res) &#123;</span><br><span class="line">            console.log(res);</span><br><span class="line">            wx.showToast(&#123;</span><br><span class="line">              title: &#x27;保存到相册成功&#x27;,</span><br><span class="line">              duration: 1500,</span><br><span class="line">            &#125;)</span><br><span class="line">          &#125;,</span><br><span class="line">          fail(res) &#123;</span><br><span class="line">            console.log(res)</span><br><span class="line">            wx.showToast(&#123;</span><br><span class="line">              title: &#x27;保存到相册失败&#x27;,</span><br><span class="line">              icon: &#x27;fail&#x27;</span><br><span class="line">            &#125;)</span><br><span class="line">          &#125;,</span><br><span class="line">          complete(res) &#123;</span><br><span class="line">            console.log(res)</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<h1 id="开源"><a href="#开源" class="headerlink" title="开源"></a>开源</h1><p>本着开源的精神，源码已经放在<code>Github</code>上，大家可以去上面查看具体代码。</p>
<p><a target="_blank" rel="noopener" href="https://github.com/HistoryZhang/SgsNoteBook">https://github.com/HistoryZhang/SgsNoteBook</a></p>
<p>如果对你有帮助的话，麻烦给个<code>Star</code>吧~</p>
<p>点击阅读原文可以查看更好的代码格式~</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E5%B0%8F%E7%A8%8B%E5%BA%8F-Canvas/" rel="tag"># 小程序, Canvas</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2018/02/07/%E5%85%AC%E4%BC%97%E5%8F%B7%E6%8E%A8%E8%8D%90/" rel="prev" title="公众号推荐">
      <i class="fa fa-chevron-left"></i> 公众号推荐
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/01/26/Flutter%E5%88%9D%E4%BD%93%E9%AA%8C/" rel="next" title="Flutter初体验">
      Flutter初体验 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BC%95%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">引言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%B9%BF%E5%91%8A"><span class="nav-number">2.</span> <span class="nav-text">广告</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%AD%A3%E6%96%87"><span class="nav-number">3.</span> <span class="nav-text">正文</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%AD%A6%E5%B0%86%E5%9B%BE%E7%89%87"><span class="nav-number">3.0.1.</span> <span class="nav-text">武将图片</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B0%8F%E7%A8%8B%E5%BA%8F%E7%A0%81"><span class="nav-number">3.0.2.</span> <span class="nav-text">小程序码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%AD%A6%E5%B0%86%E6%96%87%E5%AD%97%E4%BF%A1%E6%81%AF"><span class="nav-number">3.0.3.</span> <span class="nav-text">武将文字信息</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BB%98%E5%88%B6%E7%BD%91%E7%BB%9C%E5%9B%BE%E7%89%87"><span class="nav-number">3.0.4.</span> <span class="nav-text">绘制网络图片</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BF%9D%E5%AD%98%E5%9B%BE%E7%89%87"><span class="nav-number">3.0.5.</span> <span class="nav-text">保存图片</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BC%80%E6%BA%90"><span class="nav-number">4.</span> <span class="nav-text">开源</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Kelvin</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">57</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
        <span class="site-state-item-count">56</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/KelvinQQ" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;KelvinQQ" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:history_zq@163.com" title="E-Mail → mailto:history_zq@163.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Kelvin</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"live2d-widget-models\\packages\\live2d-widget-model-miku"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true}});</script></body>
</html>
